CREATE PROCEDURE sp_TransferFunds
    @FromAccountID VARCHAR(20),
    @ToAccountID VARCHAR(20),
    @Amount DECIMAL(18, 2)
AS
BEGIN
    SET NOCOUNT ON;
    BEGIN TRANSACTION;
    BEGIN TRY
        -- 验证账户有效性
        IF NOT EXISTS (SELECT 1 FROM BankAccounts WHERE AccountID = @FromAccountID)
            THROW 50001, '转出账户不存在', 1;

        IF NOT EXISTS (SELECT 1 FROM BankAccounts WHERE AccountID = @ToAccountID)
            THROW 50002, '转入账户不存在', 1;

        -- 检查余额是否充足
        DECLARE @CurrentBalance DECIMAL(18, 2);
        SELECT @CurrentBalance = Balance 
        FROM BankAccounts 
        WHERE AccountID = @FromAccountID;

        IF @CurrentBalance < @Amount
            THROW 50003, '账户余额不足', 1;

        -- 执行转账
        UPDATE BankAccounts 
        SET Balance = Balance - @Amount,
            LastUpdateTime = GETDATE()
        WHERE AccountID = @FromAccountID;

        UPDATE BankAccounts 
        SET Balance = Balance + @Amount,
            LastUpdateTime = GETDATE()
        WHERE AccountID = @ToAccountID;

        COMMIT TRANSACTION;
        RETURN 0;  -- 成功代码
    END TRY
    BEGIN CATCH
        ROLLBACK TRANSACTION;
        DECLARE @ErrorMessage NVARCHAR(4000) = ERROR_MESSAGE();
        RAISERROR(@ErrorMessage, 16, 1);  -- 抛出详细错误
        RETURN -1;  -- 失败代码
    END CATCH;
END;
